<?php
require_once 'common/config.php';
require_once 'common/functions.php';

check_login();
header('Content-Type: application/json');
try {
    $db = db_connect();
    $action = $_GET['action'] ?? '';
    $id = intval($_GET['id'] ?? 0);

    switch ($action) {
        case 'status':
            handleStatusChange($db, $id);
            break;
        case 'delete':
            handleDelete($db, $id);
            break;
        default:
            throw new Exception('无效操作');
    }
} catch(Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
function handleStatusChange($db, $id) {
    $status = intval($_GET['status']);
    
    $stmt = $db->prepare("UPDATE coach_evaluate 
                         SET status = ?
                         WHERE id = ?");
    $stmt->execute([$status, $id]);
    
    if ($stmt->rowCount() > 0) {
        // 更新教练评分
        updateCoachRating($db, $id);
        echo json_encode(['success' => true]);
    } else {
        throw new Exception('状态更新失败');
    }
}
function handleDelete($db, $id) {
    $stmt = $db->prepare("DELETE FROM coach_evaluate WHERE id = ?");
    $stmt->execute([$id]);
    
    if ($stmt->rowCount() > 0) {
        updateCoachRating($db, $id);
        echo json_encode(['success' => true]);
    } else {
        throw new Exception('删除失败');
    }
}
function updateCoachRating($db, $eval_id) {
    // 获取关联教练ID
    $stmt = $db->prepare("SELECT coach_id FROM coach_evaluate WHERE id = ?");
    $stmt->execute([$eval_id]);
    $coach_id = $stmt->fetchColumn();

    // 重新计算平均分
    $stmt = $db->prepare("
        UPDATE coaches 
        SET rating = (
            SELECT ROUND(AVG(rating), 1) 
            FROM coach_evaluate 
            WHERE coach_id = ? 
            AND status = 1
        )
        WHERE id = ?
    ");
    $stmt->execute([$coach_id, $coach_id]);
}